package com.aiti.lulian.handler;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONUtil;
import com.aiti.lulian.entity.LuLianEnterpriseUser;
import com.aiti.lulian.entity.ShowUserLog;
import com.aiti.lulian.service.ILuLianEnterpriseUserService;
import com.aiti.lulian.service.IShowUserLogService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;

import java.util.List;

@Component
public class InquiryEditFailureListener {

    @Autowired
    private ILuLianEnterpriseUserService enterpriseUserService;

    @Autowired
    private IShowUserLogService showUserLogService;

    @TransactionalEventListener(phase = TransactionPhase.AFTER_ROLLBACK) // Listen for rollback events
    @Transactional(propagation = Propagation.REQUIRES_NEW) // Ensure logging is in a new transaction
    public void handleInquiryEditFailedEvent(InquiryEditFailedEvent event) {
        logEditAction(event.getUserId(), event.getO(), "2",event.getErrorInfo(),event.getModules());
    }


    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void logEditAction(String userId, Object dto, String status,String errorInfo,String modules) {
        ShowUserLog showUserLog = new ShowUserLog();
        showUserLog.setBaseId(IdUtil.simpleUUID());
        showUserLog.setUserId(userId);
        showUserLog.setBaseCreateTime(DateUtil.now());
        List<LuLianEnterpriseUser> list = enterpriseUserService.list(new QueryWrapper<LuLianEnterpriseUser>().eq("user_id", userId));
        if (list != null && list.size() > 0) {
            LuLianEnterpriseUser enterpriseUser = list.get(0);
            showUserLog.setEnterpriseId(enterpriseUser.getEnterpriseId());
        }
        showUserLog.setModules(modules);
        showUserLog.setStatus(status);
        showUserLog.setContents(JSONUtil.toJsonStr(dto));
        showUserLog.setErrorInfo(errorInfo);
        showUserLogService.save(showUserLog);
    }
}
